/* eslint-disable react/no-unknown-property */
import { useEffect, useMemo, useState } from 'react';
import { Button, Dropdown, Menu, Tooltip } from 'antd';
import { getDvaApp, history } from 'umi';
import moment from 'moment';
import { TRDefault, TRMessage } from '@/components';
import HeaderTabBar from './HeaderTabBar';
import { api_warningAlert } from './services';
import { BellOutlined, CloseOutlined } from '#/utils/antdIcons';
import AvatarDropdown from '@/components/AvatarDropdown';
import { HttpCode } from '@/utils/contacts';

import sty from './index.less';
import { useLocation } from 'umi';

import { globalThemeGroup } from '#/theme';

const DARK_ARRAY = ['/BigScreenWeb'];

let guaranteeManagementInterval = null;

const LayoutHeader = ({ menuList }) => {
  const [currentThemeKey, setCurrentThemeKey] = useState(
    localStorage.getItem('saas-theme') || 'light',
  );
  const [warning, setWarning] = useState([]);
  const [toolTipOpen, setToolTipOpen] = useState();

  const handleToggleTheme = (key) => {
    const { dispatch } = getDvaApp()._store;
    if (currentThemeKey !== key) {
      setCurrentThemeKey(key);
      dispatch({
        type: 'global/setTheme',
        payload: key,
      });
    }
  };
  const la = useLocation();

  useEffect(() => {
    if (DARK_ARRAY.includes(la.pathname)) {
      handleToggleTheme('dark');
    }
  }, [la.pathname]);
  useEffect(() => {
    // 每一小时更新一次保函管理异常数据
    (isGuaranteePage || isRetailUserPage) && fetchWarningAlert();
    if (guaranteeManagementInterval) {
      clearInterval(guaranteeManagementInterval);
      guaranteeManagementInterval = null;
    }
    guaranteeManagementInterval = setInterval(() => {
      (isGuaranteePage || isRetailUserPage) && fetchWarningAlert();
    }, 60 * 1000 * 60);
    return () => {
      if (guaranteeManagementInterval) {
        clearInterval(guaranteeManagementInterval);
        guaranteeManagementInterval = null;
      }
    };
  }, []);

  const renderThemeDropDownItems = () => (
    <Menu onClick={(e) => handleToggleTheme(e.key)}>
      {Object.values(globalThemeGroup).map((theme) => (
        <Menu.Item key={theme.key}>
          {/* <img src={theme.icon} alt="" /> */}
          {RenderIcon(theme.key)}
          {theme.label}
        </Menu.Item>
      ))}
    </Menu>
  );

  // 保函管理异常数据报警
  function hasMenuCode(list, code) {
    for (const item of list) {
      if (item.menuCode === code) {
        return true;
      }
      if (item.children && item.children.length > 0) {
        if (hasMenuCode(item.children, code)) {
          return true;
        }
      }
    }
    return false;
  }
  // 监测是否属于保函管理异常数据报警页面
  const isGuaranteePage = hasMenuCode(menuList, 'letterofGuarantee');
  // 零售用户异常数据报警
  const isRetailUserPage = hasMenuCode(menuList, 'retailUser');

  const fetchWarningAlert = async () => {
    const warnigRes = await api_warningAlert();
    if (warnigRes?.statusCode === HttpCode.SUCCESS) {
      setWarning(warnigRes?.data || []);
      // setToolTipOpen(warnigRes?.data?.length);
      setToolTipOpen(Object.keys(warnigRes?.data || {}).length);
    } else {
      TRMessage(warnigRes?.message || '接口异常');
    }
  };

  // 跳转保函管理异常页面
  const gotoGuaranteeManagement = (item = {}) => {
    const searchVal = Object.entries({ date: item?.month ? item?.month : '' } || {})
      .map(([key, val]) => `${key}=${val}`)
      .join('&');
    history.push({ pathname: '/letterofGuarantee', search: searchVal ? '?' + searchVal : '' });
    setToolTipOpen(false);
  };

  // 跳转零售用户异常页面
  const gotoRetailUserManagement = (item = {}) => {
    const searchVal = Object.entries(
      {
        // powerExchangeRetailUserName: item?.powerExchangeRetailUserName ? item?.powerExchangeRetailUserName : '',
        date: item?.offlineContractExpiryTime ? item?.offlineContractExpiryTime : '',
        type: item?.type,
      } || {},
    )
      .map(([key, val]) => `${key}=${val}`)
      .join('&');
    // history.push({ pathname: item?.menuCode, search: searchVal ? '?' + searchVal : '' });
    history.replace({ pathname: item?.menuCode });
    setToolTipOpen(false);
  };

  const renderGuaranteeManagementError = () => {
    return (
      <>
        <div className={sty.guaranteeManagement_content}>
          {!warning && <TRDefault type="emptysm" message={'暂无异常数据'} />}
          {/* 保函管理 */}
          {isGuaranteePage &&
            warning.resultDim?.map((v) => (
              <div
                key={v}
                className={sty.guaranteeManagement_content_item}
                onClick={() => gotoGuaranteeManagement(v)}
              >
                <div>
                  涉及菜单：<span style={{ color: '#ff4d4f' }}>{v?.menuName}</span>
                </div>
                <div>
                  编码：<span style={{ color: '#ff4d4f' }}>{v?.bsId}</span>
                </div>
                <div>
                  市场成员名称：<span style={{ color: '#ff4d4f' }}>{v?.name}</span>
                </div>
                <div>
                  到期日期：
                  <span style={{ color: '#ff4d4f' }}>
                    {moment(v?.endTime)?.format('YYYY-MM-DD')}
                  </span>
                </div>
              </div>
            ))}
          {/* 零售用户 */}
          {isRetailUserPage &&
            warning.resultRet?.map((v) => (
              <div
                key={v}
                className={sty.guaranteeManagement_content_item}
                onClick={() => gotoRetailUserManagement(v)}
              >
                <div>
                  涉及菜单：<span style={{ color: '#ff4d4f' }}>{v?.menuName}</span>
                </div>
                <div>
                  编码：<span style={{ color: '#ff4d4f' }}>{v?.dataId}</span>
                </div>
                <div>
                  零售用户名称：
                  <span style={{ color: '#ff4d4f' }}>{v?.powerExchangeRetailUserName}</span>
                </div>
                <div>
                  到期日期：
                  <span style={{ color: '#ff4d4f' }}>
                    {moment(v?.offlineContractExpiryTime)?.format('YYYY-MM-DD')}
                  </span>
                </div>
              </div>
            ))}
        </div>
        <div style={{ textAlign: 'right' }}>
          <Button type="link" onClick={() => setToolTipOpen(false)}>
            关闭
          </Button>
        </div>
      </>
    );
  };

  const renderHeadeView = () => {
    return (
      <div className={sty.flexBox}>
        <div className={sty.left} />
        <div className={sty.rightView}>
          <div className={sty.tools}>
            {(isGuaranteePage || isRetailUserPage) && (
              <Tooltip title={renderGuaranteeManagementError()} visible={toolTipOpen}>
                <BellOutlined
                  onClick={(e) => {
                    e.stopPropagation();
                    setToolTipOpen(true);
                  }}
                  className={sty.errorIcon}
                />
              </Tooltip>
            )}
          </div>
          <div className={sty.tools}>
            <div className={sty.toolItem}>
              <Dropdown
                overlayClassName={sty.headerToggleThemeDropdownOverlay}
                overlay={renderThemeDropDownItems()}
              >
                <img src={globalThemeGroup[currentThemeKey].icon} alt="" />
              </Dropdown>
            </div>
          </div>
          <div className={sty.userView}>
            <AvatarDropdown />
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className={sty.LayoutHeader_Com_Container}>
      {renderHeadeView()}
      <HeaderTabBar />
    </div>
  );
};

export default LayoutHeader;

const RenderIcon = (key = 'light') => {
  if (key === 'light') {
    return (
      <svg
        width="20"
        height="20"
        viewBox="0 0 20 20"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path
          fill-rule="evenodd"
          clip-rule="evenodd"
          d="M4.49567 9.99986C4.49567 6.9599 6.96005 4.49554 10 4.49554C13.04 4.49554 15.5044 6.9599 15.5044 9.99986C15.5044 13.0398 13.04 15.5042 10 15.5042C6.96005 15.5042 4.49567 13.0398 4.49567 9.99986ZM10 5.89554C7.73324 5.89554 5.89567 7.73311 5.89567 9.99986C5.89567 12.2666 7.73324 14.1042 10 14.1042C12.2668 14.1042 14.1044 12.2666 14.1044 9.99986C14.1044 7.73311 12.2668 5.89554 10 5.89554Z"
          fill="var(--font)"
        />
        <path
          d="M10.0001 3.34787C10.5103 3.34787 10.924 2.93423 10.924 2.42397C10.924 1.91371 10.5103 1.50006 10.0001 1.50006C9.48983 1.50006 9.07617 1.91371 9.07617 2.42397C9.07617 2.93423 9.48983 3.34787 10.0001 3.34787Z"
          fill="var(--font)"
        />
        <path
          d="M15.3586 5.5651C15.8689 5.5651 16.2825 5.15145 16.2825 4.64119C16.2825 4.13093 15.8689 3.71729 15.3586 3.71729C14.8483 3.71729 14.4347 4.13093 14.4347 4.64119C14.4347 5.15145 14.8483 5.5651 15.3586 5.5651Z"
          fill="var(--font)"
        />
        <path
          d="M17.5761 10.9236C18.0863 10.9236 18.5 10.5099 18.5 9.99965C18.5 9.4894 18.0863 9.07574 17.5761 9.07574C17.0658 9.07574 16.6522 9.4894 16.6522 9.99965C16.6522 10.5099 17.0658 10.9236 17.5761 10.9236Z"
          fill="var(--font)"
        />
        <path
          d="M15.3586 16.2823C15.8689 16.2823 16.2825 15.8687 16.2825 15.3584C16.2825 14.8482 15.8689 14.4345 15.3586 14.4345C14.8483 14.4345 14.4347 14.8482 14.4347 15.3584C14.4347 15.8687 14.8483 16.2823 15.3586 16.2823Z"
          fill="var(--font)"
        />
        <path
          d="M10.0001 18.4998C10.5103 18.4998 10.924 18.0861 10.924 17.5759C10.924 17.0656 10.5103 16.652 10.0001 16.652C9.48983 16.652 9.07617 17.0656 9.07617 17.5759C9.07617 18.0861 9.48983 18.4998 10.0001 18.4998Z"
          fill="var(--font)"
        />
        <path
          d="M4.64126 16.2823C5.15152 16.2823 5.56517 15.8687 5.56517 15.3584C5.56517 14.8482 5.15152 14.4345 4.64126 14.4345C4.131 14.4345 3.71735 14.8482 3.71735 15.3584C3.71735 15.8687 4.131 16.2823 4.64126 16.2823Z"
          fill="var(--font)"
        />
        <path
          d="M2.42391 10.9236C2.93417 10.9236 3.34783 10.5099 3.34783 9.99965C3.34783 9.4894 2.93417 9.07574 2.42391 9.07574C1.91365 9.07574 1.5 9.4894 1.5 9.99965C1.5 10.5099 1.91365 10.9236 2.42391 10.9236Z"
          fill="var(--font)"
        />
        <path
          d="M4.64126 5.5651C5.15152 5.5651 5.56517 5.15145 5.56517 4.64119C5.56517 4.13093 5.15152 3.71729 4.64126 3.71729C4.131 3.71729 3.71735 4.13093 3.71735 4.64119C3.71735 5.15145 4.131 5.5651 4.64126 5.5651Z"
          fill="var(--font)"
        />
      </svg>
    );
  } else if (key === 'dark') {
    return (
      <svg
        width="20"
        height="20"
        viewBox="0 0 20 20"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path
          fill-rule="evenodd"
          clip-rule="evenodd"
          d="M9.18584 4.23592C6.43369 4.71227 4.34053 7.11168 4.34053 9.99998C4.34053 13.2308 6.95966 15.85 10.1905 15.85C13.0788 15.85 15.4782 13.7568 15.9546 11.0047C15.0874 11.8802 13.8844 12.4227 12.5542 12.4227C9.91071 12.4227 7.76781 10.2798 7.76781 7.63635C7.76781 6.30608 8.31028 5.10311 9.18584 4.23592ZM3.04053 9.99998C3.04053 6.05114 6.24169 2.84998 10.1905 2.84998C10.6861 2.84998 11.1705 2.90048 11.6387 2.99685C11.9346 3.05776 12.1496 3.31455 12.1574 3.61659C12.1653 3.91862 11.964 4.18625 11.6716 4.26248C10.1731 4.65317 9.06781 6.01649 9.06781 7.63635C9.06781 9.56182 10.6287 11.1227 12.5542 11.1227C14.174 11.1227 15.5373 10.0174 15.928 8.51887C16.0042 8.22651 16.2718 8.02521 16.5739 8.03307C16.8759 8.04092 17.1327 8.25586 17.1936 8.55179C17.29 9.02 17.3405 9.50444 17.3405 9.99998C17.3405 13.9488 14.1394 17.15 10.1905 17.15C6.24169 17.15 3.04053 13.9488 3.04053 9.99998Z"
          fill="var(--font)"
        />
      </svg>
    );
  } else if (key === 'gre') {
    return (
      <svg
        width="20"
        height="20"
        viewBox="0 0 20 20"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path
          fill-rule="evenodd"
          clip-rule="evenodd"
          d="M2.29999 9.99999C2.29999 5.74742 5.74742 2.29999 9.99999 2.29999C14.2526 2.29999 17.7 5.74742 17.7 9.99999C17.7 14.2526 14.2526 17.7 9.99999 17.7C5.74742 17.7 2.29999 14.2526 2.29999 9.99999ZM9.99999 3.69999C6.52061 3.69999 3.69999 6.52061 3.69999 9.99999C3.69999 13.4794 6.52061 16.3 9.99999 16.3C13.4794 16.3 16.3 13.4794 16.3 9.99999C16.3 6.52061 13.4794 3.69999 9.99999 3.69999Z"
          fill="var(--font)"
        />
        <path
          fill-rule="evenodd"
          clip-rule="evenodd"
          d="M10.4836 4.57825C7.48924 4.57825 5.06183 7.00566 5.06183 10C5.06183 12.9944 7.48924 15.4218 10.4836 15.4218"
          fill="var(--font)"
        />
      </svg>
    );
  }
};
